//
// Created on 2025/7/21.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include "utils.h"
#include <iomanip>
#include <random>
#include <sstream>
#include <chrono>
#include <iostream>
#include <filemanagement/file_uri/oh_file_uri.h>
#include <multimedia/player_framework/native_avformat.h>
#include <multimedia/player_framework/native_avcodec_base.h>

std::string GenerateUniqueId()
{
    auto now = std::chrono::system_clock::now();
    auto timeStamp = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
    
    static std::mt19937 rng(std::random_device{}());
    static std::uniform_int_distribution<> dist(1000, 9999);
    
    std::stringstream ss;
    ss << timeStamp << "_" << dist(rng);
    
    return ss.str();
}

std::string GenerateUniqueId(const std::string& tag)
{ 
    return GenerateUniqueId() + "_" + tag;
}

std::string timestamp_filename() {
    auto now = std::chrono::system_clock::now();
    auto time_t = std::chrono::system_clock::to_time_t(now);
    std::tm tm = *std::localtime(&time_t);

    std::ostringstream oss;
    oss << std::put_time(&tm, "%Y-%m-%d_%H-%M-%S") << ".mp4";
    return oss.str();
}

std::string UriToPath(const std::string& fileUri) {
 
    uint32_t length = fileUri.size();
    char* path = nullptr;
    
    FileManagement_ErrCode ret = OH_FileUri_GetPathFromUri(fileUri.c_str(), length ,&path); 
    
    if (ret != 0 && path != nullptr) {
        LOGE("Get Uri failed");
        return "";
    }
    std::string res(path);
    
    if (path != nullptr) {
        free(path);
        path = nullptr;
    }
    return res;
}    

std::string PathToUri(const std::string &path) {
    uint32_t length = path.size();
    char* fileUri = nullptr;
    
    FileManagement_ErrCode ret = OH_FileUri_GetUriFromPath(path.c_str(), length, &fileUri);
    
    if (ret != 0 | fileUri == nullptr) {
        LOGE("Get uri failed");
        return "";
    }
    
    std::string res(fileUri);
    
    if (fileUri == nullptr) {
        free(fileUri);
        fileUri = nullptr;
    }
    return res;
}
